package com.jy.rhin.domain.document.node;

import com.jy.api.upload.UploadAPI;
import com.jy.api.upload.dto.Base64FileDto;
import com.jy.framework.base.entity.Result;
import com.jy.framework.base.exception.BaseException;
import com.jy.rhin.infra.repo.node.po.NodeAuthenticationPo;
import com.jy.rhin.infra.uitl.CertAndKey;
import com.jy.rhin.infra.uitl.CertificateUtils;
import com.jy.rhin.infra.uitl.ExcelUtils;
import com.jy.rhin.infra.uitl.Utils;
import com.jy.rhin.sdk.dto.node.NodeAuthenticationDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 *
 */
@Service
@Slf4j
public class NodeAuthenticationService {

    @Autowired
    private UploadAPI uploadAPI;

    @Autowired
    private NodeAuthenticationDao nodeAuthenticationDao;



   public void addOrUpdateNode(NodeAuthenticationDto nodeAuthenticationDto){
       NodeAuthenticationPo nodeAuthenticationPo = new NodeAuthenticationPo();
       BeanUtils.copyProperties(nodeAuthenticationDto,nodeAuthenticationPo);
        if(nodeAuthenticationDto.getId()!=null){
            nodeAuthenticationDao.update(nodeAuthenticationPo);
        }else{
            nodeAuthenticationDao.save(nodeAuthenticationPo);
        }
    }

    public void auditNode(NodeAuthenticationDto nodeAuthenticationDto){
        String zhengShuSYZ = Utils.ToFirstChar(nodeAuthenticationDto.getChangshang());
       if("1".equals(nodeAuthenticationDto.getShenhezt())){
           CertAndKey certAndKey = CertificateUtils.createRootCACert(nodeAuthenticationDto.getStarTime(),nodeAuthenticationDto.getEndTime(),zhengShuSYZ);
           nodeAuthenticationDto.setPublicKey(Base64.getEncoder().encodeToString(certAndKey.getKeyPair().getPublic().getEncoded()));
           nodeAuthenticationDto.setPrivateKey(Base64.getEncoder().encodeToString(certAndKey.getKeyPair().getPrivate().getEncoded()));
           nodeAuthenticationDto.setCrtFile(uploadBase64(CertificateUtils.createCrt(certAndKey),"crt"));
           nodeAuthenticationDto.setPriFile(uploadBase64(CertificateUtils.createPriFile(certAndKey),"key"));
           String pwd =nodeAuthenticationDto.getId().toString();

           nodeAuthenticationDto.setPfxFile(uploadBase64(CertificateUtils.createPfx(certAndKey,pwd,pwd),"pfx"));
       }
        NodeAuthenticationPo nodeAuthenticationPo = new NodeAuthenticationPo();
        BeanUtils.copyProperties(nodeAuthenticationDto,nodeAuthenticationPo);
        nodeAuthenticationDao.update(nodeAuthenticationPo);
    }

    public String uploadBase64(String base64,String fileType){
       String fileAddress = "";
        Base64FileDto base64FileDto = new Base64FileDto();
        base64FileDto.setServiceName("infra");
        base64FileDto.setBase64String(base64);
        base64FileDto.setFileType(fileType);
       Result result = uploadAPI.upload(base64FileDto);
       if(result==null||result.getData()==null){
           throw new BaseException("生成文件内容证书错误");
       }

        String aliNetwork = uploadAPI.getAliNetwork(String.valueOf(result.getData()));
        try {
            InputStream inputStream = ExcelUtils.getInputStream(aliNetwork);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            String base64String = Base64.getEncoder().encodeToString( new String(outputStream.toByteArray(), StandardCharsets.UTF_8).getBytes());
            Base64FileDto base64FileDtonnew = new Base64FileDto();
            base64FileDtonnew.setServiceName("infra");
            base64FileDtonnew.setBase64String(base64String);
            base64FileDtonnew.setFileType(fileType);
            Result wenJianResult = uploadAPI.upload(base64FileDto);
            if(result==null||wenJianResult.getData()==null){
                throw new BaseException("生成文件证书错误");
            }
            fileAddress = String.valueOf(wenJianResult.getData());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  fileAddress;
    }



}
